package cn.gaaidou.dynamic.proxy.jdk.session;

import cn.gaaidou.dynamic.proxy.jdk.proxy.MapperProxy;

import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Martin
 * @date 2021/7/14 19:21
 */
public class SqlSession {

    private static final Map<String, Object> MAPPER_CACHE = new ConcurrentHashMap<>();

    /**
     * @param clazz
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public <T> T getMapper(Class<T> clazz) {
        if (MAPPER_CACHE.containsKey(clazz.getName())) {
            return (T) MAPPER_CACHE.get(clazz.getName());
        } else {
            Object mapperProxy = Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[]{clazz}, new MapperProxy());
            MAPPER_CACHE.put(clazz.getName(), mapperProxy);
            return (T) mapperProxy;
        }

    }
}
